<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/12
 * Time: 8:45
 */

namespace app\admin\controller;


use app\common\controller\AdminBase;
use other\Tree;
use think\Db;
use think\Url;

class HtmlCache extends AdminBase
{
    //生成首页
    public function createHomePage()
    {
        $chk = check_juri(request()->controller(), 'createHomePage', $this->_juri);
        if ($chk['status'])
        {
            $config = config('url_rewrite');
            return view('home_page', [
                'status' => $config
            ]);
        } else {
            $this->error($chk['msg'], url('admin/index/index'), 3);
        }
    }

    //执行生成首页
    public function doCreateHomePage()
    {
        $url_html_suffix = config('url_html_suffix');
        $url             = config('site_domain');
        $path = ROOT_PATH.'index.'.$url_html_suffix;
        if (file_exists($path))
        {
            @unlink($path);
        }
        $res = $this->sendPost($url);
        return true;
    }

    //生成栏目页
    public function createCategoryPage()
    {
        $chk = check_juri(request()->controller(), 'createCategoryPage', $this->_juri);
        if ($chk['status'])
        {
            $config = config('url_rewrite');
            $list = Db::name('category')
                ->field('id, title, parentid, attr')
                ->order('sort desc, create_time desc')
                ->select();
            $tree = new Tree($list);
            $list = $tree->get_tree(0);
            return view('category_page', [
                'status' => $config,
                'list'   => $list
            ]);
        } else {
            $this->error($chk['msg'], url('admin/index/index'), 3);
        }
    }

    //生成缓存列表
    public function categoryUpdate()
    {
        $category = intval(input('param.category'));
        $status   = intval(input('param.status'));
        if ($category != 0)
        {
            if ($status)
            {
                $cateList = $this->getTotalCategory($category);
                $urlList  = $this->getUrlList($cateList);
            } else {
                $urlList  = $this->getUrlList([$category]);
            }
            cache('category_url_list', $urlList);
        } else {
            //生成所有栏目
            $cateList = $this->getTotalCategory(0);
            $urlList  = $this->getUrlList($cateList);
        }
        return $urlList;
    }

    //生成静态文件
    public function frameHtml()
    {
        $type = intval(input('param.type'));
        $list = cache('category_url_list');
        if ($type)
        {
            $key  = intval(input('param.k'));
            $url  = config('site_domain').$list[$key];
            $this->sendPost($url);
        } else {
            return false;
        }
        $per = round(($key+1)/count($list)*100);
        return [
            'type'  => $type,
            'key'   => $key,
            'total' => count($list),
            'per'   => $per
        ];
    }

    //清空缓存
    public function clearCache()
    {
        $chk = check_juri(request()->controller(), 'clearCache', $this->_juri);
        if ($chk['status'])
        {
            $config = config('url_rewrite');
            return view('clear_cache', [
                'status' => $config
            ]);
        } else {
            $this->error($chk['msg'], url('admin/index/index'), 3);
        }
    }

    //执行清空缓存
    public function doClearCache()
    {
        if (request()->isAjax())
        {
            $type = input('param.type');
            if ($type == 'pc')
            {
                $path1 = RUNTIME_PATH.'home/';
            } else {
                $path1 = RUNTIME_PATH.'mobile/';
            }
            $path2 = RUNTIME_PATH.'temp/';
            $path3 = RUNTIME_PATH.'log/';
            deldir($path1);
            deldir($path2);
            deldir($path3);
            return true;
        }
    }

    /**
     * 发送数据
     * @param $url
     * @return mixed
     */
    protected function sendPost($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $p = curl_exec($ch);
        curl_close($ch);
        return $p;
    }


    //获取url数组
    protected function getUrlList($category)
    {
        $pcUrlList     = [];
        $mobileUrlList = [];
        Url::root('/');
        $categorys     = Db::name('category')
            ->field('id, type, url')
            ->where('id', 'in', $category)
            ->select();
        $articles      = Db::name('article')
            ->field('id')
            ->where('category_id', 'in', $category)
            ->where('status', 1)
            ->where('del_status', 0)
            ->select();
        foreach ($categorys as $val) {
            if (empty($val['url']))
            {
                if ($val['type'] == 1)
                {
                    $pcUrl     = Url::build('home/news/index', 'id='.$val['id']);
                    $mobileUrl = Url::build('mobile/news/index', 'id='.$val['id']);
                } else {
                    $pcUrl     = Url::build('home/info/index', 'id='.$val['id']);
                    $mobileUrl = Url::build('mobile/info/index', 'id='.$val['id']);
                }
                array_push($pcUrlList, $pcUrl);
                array_push($mobileUrlList, $mobileUrl);
            }

        }
        foreach ($articles as $key => $value) {
            $pcUrl     = Url::build('home/article/index', 'id='.$value['id']);
            $mobileUrl = Url::build('mobile/article/index', 'id='.$value['id']);
            array_push($pcUrlList, $pcUrl);
            array_push($mobileUrlList, $mobileUrl);
        }
        return array_merge($pcUrlList, $mobileUrlList);
    }

    //获取栏目id数组
    protected function getTotalCategory($category)
    {
        $list   = Db::name('category')
            ->field('id, title, parentid, attr')
            ->order('sort desc, create_time desc')
            ->select();
        $tree   = new Tree($list);
        $result = $tree->get_child_key($category);
        return $result;
    }
}